package cn.org.custom.server.handler;

import cn.org.custom.message.PongMessage;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;


/**
 * ChannelDuplexHandler 可以同时作为入站和出站处理器
 * 处理假链接【连接超时等占用资源的channel】
 * 客户端每隔3秒发送心跳数据包 避免被关闭
 */
public class HeartBeatHandler extends ChannelDuplexHandler {
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent stateEvent = (IdleStateEvent) evt;
            if (stateEvent.state() == IdleState.READER_IDLE) {
                ctx.writeAndFlush(new PongMessage("心跳超时")).sync();
                ctx.close();
            }
        }
    }
}
